from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from datetime import timedelta, datetime

import jose
from jose import jwt

SECRET_KEY: str = "yo5mCDHCnhOtyI60GPmuolPVYvX9pQzQQ1kdMwWMqcM"

# 60 minutes * 24 hours * 8 days = 8 days
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 2

ALGORITHM = "HS256"


def create_access_token(subject, expires_delta: timedelta = None) -> str:
    """
    生成一个 jwt token
    :param subject: token里存放的信息， 一般存放用户id
    :param expires_delta: 过期时间,单位：分钟
    :return:
    """
    now = datetime.utcnow()
    if expires_delta:
        expire = now + expires_delta
    else:
        expire = now + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)

    '''
    payload参数说明
        exp: 过期时间
        iat: 发布时间
        iss: 发布者
        sub: 面向的用户
    '''
    payload = {"exp": expire, "iat": now, "iss": "Jimmy", "sub": str(subject)}

    encoded_jwt = jose.jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

    return encoded_jwt


def token_to_sub(token_str: str):
    """
    解码token

    jwt.decode 的异常：
        token过期：jose.exceptions.ExpiredSignatureError
        token无效：jose.exceptions.JWTError
        所有异常：jose.jwt.JWTError

    :param token_str:
    :return:
    """
    try:
        payload = jwt.decode(token_str, SECRET_KEY, algorithms=[ALGORITHM])
        return payload.get('sub')

    except jose.exceptions.ExpiredSignatureError:
        return 'timeout'

    except jose.exceptions.JWTError:
        return 'fail'



# if __name__ == '__main__':
#     # 1. 生成一个 jwt token
#     user_id = {'id': 11, 'name': 'xiaopang'}
#     token = create_access_token(user_id, timedelta(minutes=1))
#     print(f"生成的token：{token}")
#
#     # 2. 获取 jwt token 里的用户id
#     ret = token_to_sub(token)
#     print(f"从token中获取到的用户id为:{ret}")


